package com.dek.grpc.helloworld;

import com.dek.grpc.dto.HelloReply;
import com.dek.grpc.dto.HelloRequest;
import com.dek.grpc.service.HelloServiceGrpc;
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
import io.grpc.StatusRuntimeException;

import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;

public class HelloWorldClient {

    private static final Logger LOGGER = Logger.getLogger(HelloWorldClient.class.getName());

    private final ManagedChannel channel;
    private final HelloServiceGrpc.HelloServiceBlockingStub blockingStub;

    public HelloWorldClient(ManagedChannel channel) {
        this.channel = channel;
        blockingStub = HelloServiceGrpc.newBlockingStub(channel);
    }

    public HelloWorldClient(String host, int port) {
        this(ManagedChannelBuilder.forAddress(host, port).usePlaintext().build());
    }

    public void shutdown() throws InterruptedException {
        channel.shutdown().awaitTermination(5, TimeUnit.SECONDS);
    }

    public void greet(String name) {
        LOGGER.info("will try to greet " +name+ "..." );
        HelloRequest request = HelloRequest.newBuilder().setName(name).build();
        HelloReply response;
        try {
            response = blockingStub.sayHello(request);
        } catch (StatusRuntimeException e) {
            LOGGER.log(Level.WARNING, "rpc failed : {0}", e.getStatus());
            return;
        }
        LOGGER.info("greeting : " + response.getMessage());
    }

    public static void main(String[] args) throws InterruptedException {
        HelloWorldClient client = new HelloWorldClient("localhost", 5001);
        try {
            String user = "world";
            client.greet(user);
        } finally {
            client.shutdown();
        }
    }



}
